package com.yint.server;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.yint.core.AbsHandler;

public class Acceptor extends AbsHandler {

	private final ServerSocketChannel ssc;
	private final int cores = Runtime.getRuntime().availableProcessors();
	private int selIdx = 0;
	private TCPSubReactor[] subReactors = new TCPSubReactor[cores];
	private ExecutorService executor = Executors.newFixedThreadPool(cores);

	public Acceptor(Selector selector, ServerSocketChannel ssc) throws IOException {
		this.ssc = ssc;
		for (int i = 0; i < cores; i++) {
			TCPSubReactor subReactor = new TCPSubReactor(Selector.open(), i);
			executor.execute(subReactor);
			subReactors[i] = subReactor;
		}
	}

	@Override
	protected void onHandler(SelectionKey selectedKeys) throws IOException {
		System.out.println("Acceptor runing...");
		// 接受client链接请求
		SocketChannel sc = ssc.accept();
		System.out.println(sc.socket().getRemoteSocketAddress().toString() + " is connected.");

		if (sc != null) {
			// 设置为非阻塞
			sc.configureBlocking(false);
			subReactors[selIdx].register(sc,SelectionKey.OP_READ);
			if (++selIdx == subReactors.length) {
				selIdx = 0;
			}
		}
	}

}
